package com.example.springbootbabyu.controller;


import com.example.springbootbabyu.entity.LoginDTO;
import com.example.springbootbabyu.entity.LoginVO;
import com.example.springbootbabyu.entity.RegisterDTO;
import com.example.springbootbabyu.exception.UnauthorizedException;

import com.example.springbootbabyu.service.UserService;

import com.example.springbootbabyu.utils.JwtTokenUtil;
import com.example.springbootbabyu.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;



/**
 * 功能
 * 作者：梦天
 * 日期：2025/4/19 19:03
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    private final JwtTokenUtil jwtTokenUtil;
    private UserController(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }
    @PostMapping("/login")
    public ResultUtil<LoginVO> login(@RequestBody LoginDTO loginDTO) {
        log.info("登录请求参数：{}", loginDTO);
        if (loginDTO == null || loginDTO.getAccount() == null || loginDTO.getPassword() == null) {
//            return ResultUtil.error(400, "用户名或密码不能为空");
            throw new UnauthorizedException("用户名或密码不能为空");
        }
        LoginVO result = userService.login(loginDTO);
        if (result == null){
            throw new UnauthorizedException("用户名或密码错误");
//            return ResultUtil.error(400, "用户名或密码错误");
        }

//        ResultUtil<LoginVO> resultUtil = new ResultUtil<>();
//        resultUtil.setCode(1);
//        resultUtil.setMsg("登录成功");
//        resultUtil.setResult(result);
//        log.info("登录成功{}", result);
//        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
//        operations.set(result.getToken(),result.getToken(),1, TimeUnit.HOURS);
        return ResultUtil.success(1, "登录成功", result);
    }
    @PostMapping("/logout")
    public ResultUtil<String> logout(@RequestHeader(name = "Authorization") String token) {
        log.info("登出请求参数：{}", token);
        if (token == null) {
            throw new UnauthorizedException("token不能为空");
        }
        jwtTokenUtil.deleteToken(token);
        return ResultUtil.success(1, "登出成功", "登出成功");
    }
    @PostMapping("/register")
    public ResultUtil register(@RequestBody RegisterDTO registerDTO) {
        log.info("注册请求参数：{}", registerDTO);
        if (registerDTO == null || registerDTO.getAccount() == null || registerDTO.getPassword() == null) {
            return ResultUtil.error(400, "用户名或密码不能为空");
        }

        boolean result = userService.register(registerDTO);
        if (result) {
            return ResultUtil.success(1, "注册成功", "注册成功");
        } else {
            return ResultUtil.error(400, "账号已存在");
        }
    }
}
